
import { Result, ResultError } from "@/types";
import { inArray } from "./data/array";
import { routeRedirectTo } from "@/utils/route"
import { useConfig } from "@/store";

export const setStorage = (key: string, value: any, time = 0) => {
    uni.setStorageSync(key,
        JSON.stringify({ data: value, time: time == 0 ? -1 : (new Date().getTime() + time * 1000) })
    )
}

export const getStorage = (key: string) => {
    let data = uni.getStorageSync(key)
    if (!data) return null
    let dataObj = JSON.parse(data)
    if (dataObj.time != -1 && dataObj.time < new Date().getTime()) {
        localStorage.removeItem(key)
        return null
    } else {
        return dataObj.data
    }
}

export const getDiyData = () => {
    let t = this, diyData = useConfig().getDiyData
    if (!diyData) {
        routeRedirectTo('/pages/index/init')
    } else {
        useConfig().initDiyData();
        return diyData;
    }
}

export const errorMsg = (res: ResultError) => {
    if (res.code == 'SERVER_ERRPR') {
        uni.showToast({
            title: res?.data?.message || '服务器请求错误，请稍后再试',
            icon: "none"
        })
    } else if (res.code == 'ERRPR' || res.code == ' ERRPR_AUTH') {
        uni.showToast({
            title: res?.data?.message || '未知错误',
            icon: "none"
        })
    } else if (typeof res == 'string') {
        uni.showToast({
            title: res || '处理失败!',
            icon: "none"
        })
    }
}


export const successMsg = (res: Result | string) => {
    if (typeof res == 'string') {
        uni.showToast({
            title: res,
            icon: "none"
        })
    } else if (typeof res == 'object') {
        uni.showToast({
            title: res?.message || '处理成功！',
            icon: "none"
        })
    }
}


/**
 * 图片路径转换
 */
export const staticimg = (imgPath: string, params: {
    size?: string;
} = {}) => {
    var path = "";
    if (imgPath && imgPath != undefined && imgPath != "") {
        if (params.size && imgPath != getDefaultImage().default_goods_img) {
            // 过滤默认图
            let arr = imgPath.split(".");
            let suffix = arr[arr.length - 1];
            arr.pop();
            arr[arr.length - 1] = arr[arr.length - 1] + "_" + params.size?.toUpperCase() || '0';
            arr.push(suffix);
            imgPath = arr.join(".");
        }
        if (imgPath.indexOf("http://") == -1 && imgPath.indexOf("https://") == -1) {
            path = import.meta.env.VITE_BASE_URL + '/static/common/image/web/' + imgPath;
        } else if (imgPath != '') {
            path = imgPath;
        }
    } else {
        path = import.meta.env.VITE_BASE_URL + '/static/common/image/web/empty-img.png';
    }
    return path;
}

/**
 * 获取默认图
 */
export const getDefaultImage = () => {
    let defaultImg = getStorage('DEFAULTIMG');
    if (defaultImg) {
        defaultImg = JSON.parse(defaultImg);
        defaultImg.default_goods_img = staticimg(defaultImg.default_goods_img);
        defaultImg.default_headimg = staticimg(defaultImg.default_headimg);
        defaultImg.default_storeimg = staticimg(defaultImg.default_storeimg);
        return defaultImg;
    } else {
        return {
            default_goods_img: '',
            default_headimg: '',
            default_storeimg: ''
        };
    }
}

export const cory = (content:string) => {
    // 使用#ifdef H5和#endif控制各端调用情况

    // 该方法不支持h5
    //#ifndef H5
    uni.setClipboardData({
        data: String(content), // 必须字符串
        success: function () {
            successMsg("复制成功")
        }
    });
    //#endif

    // h5端赋值方法，使用创建节点
    // #ifdef H5
    if (!document.queryCommandSupported('copy')) { // 兼容某些浏览器的判断
        console.log('该浏览器不支持')
    }
    let textarea = document.createElement("textarea") as any
    textarea.value = content
    textarea.readOnly = "readOnly"
    document.body.appendChild(textarea)
    textarea.select() // 选择对象
    textarea.setSelectionRange(0, content.length) // 核心
    let result = document.execCommand("copy") // 执行浏览器复制命令
    if (result) {
        uni.showToast({
            title: '复制成功',
            duration: 2000
        });
    }
    textarea.remove()
    // #endif
}

export const payment = (payData:{
    timeStamp:string;
    nonceStr:string;
    prepay_id:string;
    paySign:string;
},order:any,url:string) => {
    if(!url){
        url = '/otherpages/order/result/index'
    }
    uni.requestPayment({
        orderInfo:'',
        provider: 'wxpay',
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: 'prepay_id=' + payData.prepay_id,
        signType: 'MD5',
        paySign: payData.paySign,
        success: () => {
            routeRedirectTo(url, order,  'redirectTo');
        },
        fail: res => {
            if (res.errMsg == 'requestPayment:fail cancel') {
                successMsg('您已取消支付' );
            } else {
                successMsg('支付失败,失败原因: ' + res.errMsg);
            }
            setTimeout(() => {
                routeRedirectTo(url, order, 'redirectTo');
            }, 2000);
        }
    });
}

export default {
    setStorage,
    getStorage,
    getDiyData,
    errorMsg,
    successMsg,
    staticimg,
    cory,
    payment
}